package com.yuchen.ishop.web.app;

import com.yuchen.core.MyPager;
import com.yuchen.ishop.Gobals;
import com.yuchen.ishop.entity.Order;
import com.yuchen.ishop.service.Order.OrderRestClient;
import com.yuchen.ishop.service.goods.GoodsImgRestClient;
import com.yuchen.ishop.service.goods.GoodsRestClient;
import com.yuchen.ishop.vo.CookieUserInfo;
import com.yuchen.ishop.web.BaseAction;
import com.yuchen.utils.CookieUtils;
import com.yuchen.utils.OrderNo;
import com.yuchen.utils.security.Base64Utils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单
 */
@Controller
@RequestMapping(value = "/order")
public class OrderAction extends BaseAction {//TODO 代码重复需重构

    private final static Logger LOG = Logger.getLogger(OrderAction.class);

    @Autowired
    private GoodsRestClient goodsRestClient;

    @Autowired
    private GoodsImgRestClient goodsImgRestClient;

    @Autowired
    private OrderRestClient orderRestClient;

    @RequestMapping(value = {"goOrder"})
    public String goOrder(ModelMap modelMap, HttpServletRequest request) {
        return "redirect:/order/index.htm";
    }


    @RequestMapping(value = {"index"})
    public String index(ModelMap modelMap, HttpServletRequest request) {
        String cart = null;
        boolean flag = false;
        try {
            cart = CookieUtils.findCookie(Gobals.COOKIE_CART_ID, request);
            String[] goodsIds = StringUtils.split(cart, ",");
            if (StringUtils.isNotBlank(cart)) {
                Map params = new HashMap(2);
                params.put("pageSize", goodsIds.length);
                params.put("ids", cart);
                MyPager myPager = goodsRestClient.findByLimit(params);
                if (myPager != null && myPager.getRecords() != null && myPager.getRecords().size() > 0) {
                    List records = myPager.getRecords();
                    Map map = new HashMap(4);
                    map.put("records", records);
                    map.put("total", records.size());
                    Map m = null;
                    Double totalPrice = 0d;
                    for (int i = 0; i < records.size(); i++) {
                        m = (Map) records.get(i);
                        if (m.get("price") != null) {
                            Double price = NumberUtils.toDouble(m.get("price").toString());
                            totalPrice += price;
                        }
                        String mainUrl = goodsImgRestClient.getGoodsMainImg(NumberUtils.toLong(m.get("id").toString()));
                        m.put("photo", mainUrl);
                    }
                    map.put("totalPrice", totalPrice);
                    modelMap.addAttribute("results", map);
                    //modelMap.addAttribute("goodsIds",cart);
                    flag = true;
                }
            }
        } catch (Exception e) {
            //e.printStackTrace();
            LOG.error(e.getMessage());
        }
        if (flag) {
            return "order/index";
        }
        return "redirect:/error.htm";

    }

    @RequestMapping(value = {"confirmcart"})
    public String confirmcart(String goodsId, ModelMap modelMap, HttpServletRequest request) {
        String cart = null;
        boolean flag = false;
        try {
            cart = CookieUtils.findCookie(Gobals.COOKIE_CART_ID, request);
            if (StringUtils.isNotBlank(cart)) {
                String[] goodsIds = StringUtils.split(cart, ",");
                Map params = new HashMap(2);
                params.put("pageSize", goodsIds.length);
                params.put("ids", cart);
                MyPager myPager = goodsRestClient.findByLimit(params);
                if (myPager != null && myPager.getRecords() != null && myPager.getRecords().size() > 0) {
                    List records = myPager.getRecords();
                    Map map = new HashMap(4);
                    map.put("records", records);
                    map.put("total", records.size());
                    Map m = null;
                    Double totalPrice = 0d;
                    for (int i = 0; i < records.size(); i++) {
                        m = (Map) records.get(i);
                        if (m.get("price") != null) {
                            Double price = NumberUtils.toDouble(m.get("price").toString());
                            totalPrice += price;
                        }
                    }
                    map.put("totalPrice", totalPrice);
                    modelMap.addAttribute("results", map);
                    //modelMap.addAttribute("goodsIds",cart);
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag) {
            return "order/confirmcart";
        }
        return "redirect:/error.htm";
    }

    @RequestMapping(value = {"createcart"})
    public String createcart(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response, RedirectAttributes attr) {
        String cart = null;
        boolean flag = false;
        String orderNo = null;
        try {
            cart = CookieUtils.findCookie(Gobals.COOKIE_CART_ID, request);
            CookieUserInfo userInfo = cookie2UserInfo(request);
            String[] goodsIds = StringUtils.split(cart, ",");

            if (StringUtils.isNotBlank(cart)) {
                Map params = new HashMap(2);
                params.put("pageSize", goodsIds.length);
                params.put("ids", cart);
                MyPager myPager = goodsRestClient.findByLimit(params);
                if (myPager != null && myPager.getRecords() != null && myPager.getRecords().size() > 0) {
                    List records = myPager.getRecords();
                    Map map = new HashMap(4);
                    Map m = null;
                    orderNo = OrderNo.createNo();
                    Timestamp createTime = getTime();
                    Order order = null;
                    String role = null;
                    Double price = null;
                    for (int i = 0; i < records.size(); i++) {
                        order = new Order();
                        m = (Map) records.get(i);
                        if (m.get("price") != null) {
                            price = NumberUtils.toDouble(m.get("price").toString());
                            order.setPrice(price);
                            order.setRealPrice(price);
                        }
                        order.setGoodsId(Long.valueOf(m.get("id").toString()));
                        order.setOrderNo(orderNo);
                        order.setSubOrderNo(orderNo + (i + 1));
                        order.setCreateTime(createTime);
                        order.setSellerId(Long.valueOf(m.get("seller_id").toString()));

                        role = userInfo.getRole();
                        if ("buyer".equals(role)) {
                            order.setBuyerId(userInfo.getId());
                            order.setState(0l);
                        } else if ("seller".equals(role)) {
                            order.setState(1l);
                            order.setBuySellerId(userInfo.getId());
                        } else {
                            order.setState(1l);
                            order.setBuySellerId(userInfo.getSellerId());
                            order.setBuyXiaoerId(userInfo.getId());
                        }
                        orderRestClient.insert(order);
                        goodsRestClient.lockGoods(Long.valueOf(m.get("id").toString()));
                    }

                    modelMap.addAttribute("orderNo", orderNo);
                    modelMap.addAttribute("createTime", createTime.getTime());
                    CookieUtils.deleteCookie(Gobals.COOKIE_CART_ID, response);
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag) {
            orderNo = Base64Utils.encodeBase64(orderNo);
            attr.addAttribute("orderNo", orderNo);
            return "redirect:/order/paycart.htm";
        }
        return "redirect:/error.htm";
    }

    @RequestMapping(value = {"paycart"})
    public String paycart(String orderNo, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isBlank(orderNo))return "redirect:/error.htm";
        orderNo = Base64Utils.decodeBase64(orderNo);
        List<Order> orders = orderRestClient.findByOrderNo(orderNo);
        if (orders != null && orders.size() > 0) {
            Order order = orders.get(0);
            modelMap.addAttribute("createTime",order.getCreateTime().getTime());
            modelMap.addAttribute("orderNo",orderNo);
            Double totalPrice = 0d;
            for(Order o : orders){
                totalPrice += o.getRealPrice();
            }
            modelMap.addAttribute("totalPrice",totalPrice);
            return "order/paycart";
        }
        return "redirect:/error.htm";
    }


    @RequestMapping(value = {"deleteGoods"}, method = RequestMethod.POST)
    @ResponseBody
    public Map deleteGoods(Long goodsId, HttpServletRequest request, HttpServletResponse response) {
        Map map = errorJson();
        if (goodsId == null) return map;
        try {
            String cart = CookieUtils.findCookie(Gobals.COOKIE_CART_ID, request);
            if (StringUtils.isNotBlank(cart)) {
                String[] goodsIds = StringUtils.split(cart, ",");
                if (ArrayUtils.contains(goodsIds, goodsId.toString())) {
                    goodsIds = (String[]) ArrayUtils.removeElement(goodsIds, goodsId.toString());
                    CookieUtils.addCookie(Gobals.COOKIE_CART_ID, StringUtils.join(goodsIds, ","), CookieUtils.one_day, response);
                    map.put("success", true);
                    //计算总价
                    Double totalPrice = 0d;
                    if (goodsIds.length > 0) {
                        Map params = new HashMap(2);
                        params.put("pageSize", goodsIds.length);
                        params.put("ids", StringUtils.join(goodsIds, ","));
                        MyPager myPager = goodsRestClient.findByLimit(params);
                        if (myPager != null && myPager.getRecords() != null && myPager.getRecords().size() > 0) {
                            List records = myPager.getRecords();
                            Map m = null;
                            for (int i = 0; i < records.size(); i++) {
                                m = (Map) records.get(i);
                                if (m.get("price") != null) {
                                    Double price = NumberUtils.toDouble(m.get("price").toString());
                                    totalPrice += price;
                                }
                            }
                        }
                    }
                    map.put("totalPrice", totalPrice);
                    return map;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        return map;
    }


    //   private

}
